package com.fly;

import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;

import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.r2dbc.connectionfactory.init.ConnectionFactoryInitializer;
import org.springframework.data.r2dbc.connectionfactory.init.ResourceDatabasePopulator;

import com.fly.r2dbc.basics.dao.CustomerRepository;
import com.fly.r2dbc.basics.entity.Customer;

import io.r2dbc.spi.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootApplication
public class H2SpringApplication implements CommandLineRunner
{
    @Autowired
    CustomerRepository repository;
    
    public static void main(String[] args)
    {
        SpringApplication.run(H2SpringApplication.class, args);
    }
    
    @Override
    public void run(String... args)
        throws IOException
    {
        initDb();
        if (SystemUtils.IS_OS_WINDOWS)
        {
            String url = "http://127.0.0.1:8080";
            Runtime.getRuntime().exec("cmd /c start " + url);
            Runtime.getRuntime().exec("cmd /c start " + url + "/customer/");
            Runtime.getRuntime().exec("cmd /c start " + url + "/h2-console");
        }
    }
    
    @Bean
    ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory)
    {
        ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
        initializer.setConnectionFactory(connectionFactory);
        initializer.setDatabasePopulator(new ResourceDatabasePopulator(new ClassPathResource("schema.sql")));
        return initializer;
    }
    
    private void initDb()
    {
        // save a few customers
        repository.saveAll(Arrays.asList(new Customer("Jack", "Bauer"),
            new Customer("Chloe", "O'Brian"),
            new Customer("Kim", "Bauer"),
            new Customer("David", "Palmer"),
            new Customer("Michelle", "Dessler"),
            new Customer("Jack", "Bauer"),
            new Customer("Chloe", "O'Brian"),
            new Customer("Kim", "Bauer"),
            new Customer("David", "Palmer"),
            new Customer("Michelle", "Dessler"))).blockLast(Duration.ofSeconds(10));
        
        // fetch all customers
        log.info("Customers found with findAll():");
        log.info("-------------------------------");
        repository.findAll().doOnNext(customer -> {
            log.info(customer.toString());
        }).blockLast(Duration.ofSeconds(10));
    }
}
